from flask import request, session, jsonify
import json
import requests
from login import login_sql as ls
from common.database import DataBase

db = DataBase()
# 登录
def login():
    data = json.loads(request.get_data(as_text=True))
    try:
        if data["username"] == 'admin' and data["password"] == 'admin':
            session['user'] = data["username"]
            return jsonify({"code": 1})
        else:
            # 调用公司 公共 账号
            # r = requests.post("http://xxx/logintest/",
            #                   data=json.dumps({"username": data["username"], "password": data["password"]}))
            # r1 = r.json()
            # if r1["success"] == 'true':
            #     session['user'] = data["username"]
            #     return jsonify(r1)
            # else:
            #     return jsonify(r1)
            sql = ls.login(data)
            res = db.test_platform(sql)
            print(res)
            if len(res)==1:
                session['user'] = res[0]['username']
                return jsonify({"code": 1})
            else:
                return jsonify({"code": 0,"msg":"账号密码错误！"})
    except Exception as e:
        return jsonify({"code": 0, "msg": f"服务异常:{str(e)}"})

# 退出登录
def logout():
    username = session.get('user')
    session.clear()
    return jsonify({"code": 1, "msg": f"用户{username}退出成功"})


# 注册
def regist():
    data = json.loads(request.data)
    if data["username"] == '' :
        return {"code": 0, "msg": "注册失败,账号不能为空"}
    try:
        sql = ls.regist(data)
        # user = ls.login_username(data)
        res = db.test_platform(sql=sql,m='w')
        if res["code"] == 1:
            return jsonify(res)
        else:
            return jsonify(res)
    except Exception as e:
        return {"code": 0, "msg": "注册接口异常","result":str(e)}

# 获取session值
def get_session_value(key):
    if session.get(key) is None:
        return {"code": 0, "data": f"获取用户名失败，请检查是否登录"}
    else:
        return {"code": 1, key: session.get(key)}
